package cn.enjoy;
import cn.enjoy.service.IProductService;
import cn.enjoy.vo.Product;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
@RestController
@RequestMapping("/prodcut")
public class ProductController {

    @Resource
    private IProductService iProductService;

    @Resource
    private DiscoveryClient client ; // 进行Eureka的发现服务

    /**
     * PathVariable RequestBody 这些都是restFul 请求的
     */
    @RequestMapping(value="/get/{id}")
    @HystrixCommand(fallbackMethod = "getFallback")
    public Object get(@PathVariable("id") long id) {
        // 未加入hystrix 熔断之前
        //return  this.iProductService.get(id);

        //加入熔断之后
        Product product = this.iProductService.get(id);
        if (product == null){
            throw  new RuntimeException("该产品已下架！");
        }
        return product;
    }
    //当服务的此接口出现问题了，就调此方法
    public Object  getFallback(@PathVariable("id") long id){
        Product product = new Product();
        product.setProductName("HystrixName");
        product.setProductDesc("HystrixDesc");
        product.setProductId(0L);
        return product;
    }

    @RequestMapping(value="/add")
    public Object add(@RequestBody Product product) {
        return this.iProductService.add(product) ;
    }
    @RequestMapping(value="/list")
    public Object list() {
        return this.iProductService.list() ;
    }

    @RequestMapping("/discover")
    public Object discover() { // 直接返回发现服务信息
        return this.client;
    }
}
